'use strict'
var reports = ko.utils.parseJson( localStorage.getItem('ActiveCitizen-Reports') );

var Report = function(category, address, description) {
	this.category = ko.observable(category);
	this.address = ko.observable(address);
	this.description = ko.observable(description);
};



var ViewModelReports = function () {
	var self = this, 
		currentItem;
		
	self.person = new ViewModelPerson( ko.utils.parseJson(localStorage.getItem('ActiveCitizen-Person')) || {} );
	
	// map array of passed in todos to an observableArray of Report objects
	self.reports = ko.observableArray(ko.utils.arrayMap(reports, function(report) {
		return new Report(report.category, report.address);
	}));
	
	self.currentCategory = ko.observable();
	self.currentAddress = ko.observable();
	self.currentDescription = ko.observable();
	self.editing = ko.observable(false);
	
	$("#geocomplete").geocomplete()
          .bind("geocode:result", function(event, result){
			self.currentAddress(result.formatted_address);
			//alert(result.formatted_address);
          })
          .bind("geocode:error", function(event, status){
            alert("ERROR: " + status);
          });
	
	$("#input").geocomplete({
          map: "#map_canvas",
          //details: "form ",
          markerOptions: {
            draggable: true
          }
    });
	

	
	$("#input").bind("geocode:dragged", function(event, latLng){
          alert(latLng.lat()+','+latLng.lng());
    });
	
	
	//hello git
		
	self.add = function() {
		var category = self.currentCategory();
		var address = self.currentAddress();
		var description = self.currentDescription() || '';
		if (address) {
			self.reports.unshift(new Report(category, address.trim(), description.trim()));
		}	
	};
	
	
	self.editItem = function(item, event) {
		//console.log(event);
		currentItem = item;
		self.editing(true);
		self.currentCategory(item.category());
		self.currentAddress(item.address());
		self.currentDescription(item.description());
	};
	
	self.replaceItem = function() {
		//console.log(currentItem.address());
		var category = self.currentCategory();
		var address = self.currentAddress();
		var description = self.currentDescription() || '';
		if (address) {
			self.reports.replace(currentItem, new Report(category, address.trim(), description.trim()));
		}	
	};
	
	self.removeItem = function( item ) {
			//alert(item.address());
			self.reports.remove( item );
			//$('#footer').show();
	};
	
	ko.computed(function() {
		// store a clean copy to local storage, which also creates a dependency on the observableArray and all observables in each item
		localStorage.setItem('ActiveCitizen-Reports', ko.toJSON( self.reports ) );
	}).extend({
		throttle: 500
	}); // save at most twice per second

};